/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import models.Answers;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Vuong Pham<Vuong.Pham@hva.nl>
 */
public class QuizAnswersDao {

    private final Session session;

    /*
     * Constructor
     */
    public QuizAnswersDao(Session session) {
        this.session = session;
    }

    /*
     * Returns a list of all answers
     */
    public List<Answers> findAll() {
        Transaction tx = session.beginTransaction();
        List<Answers> list = session.createQuery("from Answers").list();
        tx.commit();
        return list;
    }

    /*
     * Returns all answers by question
     * parameter id = question id
     */
    public List<Answers> findAllbyQuestion(long id) {
        Transaction tx = session.beginTransaction();
        List<Answers> list = session.createQuery("from Answers where question_question_id = " + id).list();
        tx.commit();
        return list;
    }

    /*
     * Saves answer
     * Returns true if saved
     */
    public boolean save(Answers answer) {
        try {
            Transaction tx = session.beginTransaction();
            session.save(answer);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /*
     * Updates answer
     * Returns true if updated
     */
    public boolean update(Answers answer) {
        try {
            Transaction tx = session.beginTransaction();
            session.update(answer);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /*
     * Returns answer
     * parameter id = answer id
     */
    public Answers get(long id) {
        return (Answers) session.get(Answers.class, id);
    }

    /*
     * Deletes answer
     * parameter answer = answer object
     */
    public void delete(Answers answer) {
        Transaction tx = session.beginTransaction();
        session.delete(answer);
        tx.commit();
    }
}
